package com.leyou.auth.interceptors;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mySun
 * @create 2021-07-29 11:13
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //获取用户token
            String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
            Payload payload = jwtUtils.parseJwt(token);
            UserDetail userDetail = payload.getUserDetail();
            log.info("用户{}正在访问。", userDetail.getUsername());
            //将用户信息存入userContext中
            UserContext.setUser(userDetail);
            return true;
        }catch (JwtException e) {
            throw new LyException(401, "JWT无效或过期!", e);
        } catch (IllegalArgumentException e){
            throw new LyException(401, "用户未登录!", e);
        }
    }

}
